package com.cskaoyan.mall.controller.mall;

import com.cskaoyan.mall.model.bo.admin.AdminChangePwdBo;
import com.cskaoyan.mall.model.bo.user.UserMessageBo;
import com.cskaoyan.mall.model.bo.user.UserPwdChangeBo;
import com.cskaoyan.mall.model.bo.user.UserSignUpMessageBo;
import com.cskaoyan.mall.model.vo.user.UserLoginVo;
import com.cskaoyan.mall.model.vo.user.UserMessageVo;
import com.cskaoyan.mall.service.lmpl.UserServiceImpl;
import com.cskaoyan.mall.utils.Json;
import com.cskaoyan.mall.utils.Result;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName: MallUsersServlet
 * @Description: TODO 用户的登录和注册
 * @Auther 庄左
 * @Date 2022/7/3 15:25
 * @Version
 **/
@WebServlet("/api/mall/user/*")
public class MallUsersServlet extends HttpServlet {


    //获取json字符串
    Json json = new Json();
    private Gson gson = new Gson();
    private Result result = new Result();
    private UserServiceImpl userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String replace = requestURI.replace(req.getContextPath() + "/api/mall/user/", "");
        if ("login".equals(replace)) {
            login(req, resp);
        }
        if ("signup".equals(replace)) {
            signUp(req, resp);
        }
        if ("updateUserData".equals(replace)) {
            updateUserData(req, resp);
        }
        if ("updatePwd".equals(replace)){
            updatePwd(req,resp);
        }
        if ("logoutClient".equals(replace)){
            logoutClient(req,resp);
        }

    }

    private void logoutClient(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        req.getSession().invalidate();

        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));
        // login(req,resp);
    }

    /**
* @Author: 庄左
* @Description: 用户修改自己的密码,修改完密码应该重新登录，调用退出登录的方法
* @DateTime: 2022/7/7 20:13
*/
    private void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String reqBody = json.getJsonString(req);
        //拿到json字符串----->java对象
        UserPwdChangeBo userChangePwdBo = gson.fromJson(reqBody, UserPwdChangeBo.class);
        //获取旧密码，如何获取?
        //nickname不可重复，根据nickname取出旧密码
        //判断旧密码是否正确
        // String oldPwd = (String) req.getServletContext().getAttribute("oldPwd");
        String oldPwd = (String) req.getSession().getAttribute("oldPwd");
        if("admin".equals(oldPwd)){
            result.setCode(10000);
            result.setMessage("admin不允许修改");
            resp.getWriter().println(gson.toJson(result));
            return;
        }
        if (!userChangePwdBo.getOldPwd().equals(oldPwd)) {
            result.setCode(10000);
            result.setMessage("旧密码错误");
            resp.getWriter().println(gson.toJson(result));
            return;
        }
        //判断新密码是否与旧密码相同
        if (userChangePwdBo.getNewPwd().equals(oldPwd)) {
            result.setCode(10000);
            result.setMessage("新密码不能与旧密码相同");
            resp.getWriter().println(gson.toJson(result));
            return;
        }
        //判断新密码是否一致
        if (!userChangePwdBo.getNewPwd().equals(userChangePwdBo.getConfirmPwd())) {
            result.setCode(10000);
            result.setMessage("请保持确认新密码一致！");
            resp.getWriter().println(gson.toJson(result));
            return;
        }
        userService.changePwd(userChangePwdBo);
        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));
        //退出登录

    }

    /**
     * @Author: 庄左
     * @Description: 用户修改自己的资料，密码除外，修改密码有另外的方法
     * @DateTime: 2022/7/7 19:55
     */
    private void updateUserData(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获得请求体
        UserMessageBo userMessageBo = gson.fromJson(json.getJsonString(req), UserMessageBo.class);
        //根据id找到该用户，然后修改资料
        userService.updateUserData(userMessageBo);
        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));
    }

    /**
     * @Author: 庄左
     * @Description: 用户的注册
     * TODO:验证输入是否合法
     * @DateTime: 2022/7/3 18:34
     */
    private void signUp(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        UserSignUpMessageBo sign = gson.fromJson(json.getJsonString(req), UserSignUpMessageBo.class);

        userService.insertUser(sign);
        //用来封装返回信息的对象
        UserLoginVo userLoginVo = new UserLoginVo();
        result.setCode(0);
        userLoginVo.setCode(0);
        userLoginVo.setName(sign.getNickname());
        userLoginVo.setToken(sign.getNickname());
        result.setData(userLoginVo);
        resp.getWriter().println(gson.toJson(result));


    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        UserMessageVo userMessageVo = gson.fromJson(json.getJsonString(req), UserMessageVo.class);
        //用来封装返回信息的对象
        UserLoginVo userLoginVo = new UserLoginVo();

        if (StringUtils.isEmpty(userMessageVo.getEmail())) {
            result.setCode(10000);
            result.setMessage("用户名、密码不能为空");
            resp.getWriter().println(gson.toJson(result));
            return;
        }
        //调用Service层 的方法
        UserMessageVo login = userService.login(userMessageVo);
        if (login != null) {
            //登录成功
            result.setCode(0);
            userLoginVo.setCode(0);
            userLoginVo.setName(login.getNickname());
            userLoginVo.setToken(login.getNickname());
            //登陆成功进行这一步
            //将旧密码，用户名存入contex域/session域
            //这一步为之后的修改自身密码时与用户输入的旧密码做比对
            //以及订单页的回显精准到该用户，使其无法看到其他们用户的订单
            // req.getServletContext().setAttribute("nameToken", userMessageVo.getEmail());
            // req.getServletContext().setAttribute("oldPwd", userMessageVo.getPwd());
            HttpSession session = req.getSession();
            session.setAttribute("name", userMessageVo.getEmail());
            session.setAttribute("oldPwd", userMessageVo.getPwd());
            result.setData(userLoginVo);
            resp.getWriter().println(gson.toJson(result));
        } else {
            result.setCode(10000);
            result.setMessage("用户名、密码错误");
            resp.getWriter().println(gson.toJson(result));
            return;
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String requestURI = req.getRequestURI();
        String replace = requestURI.replace(req.getContextPath() + "/api/mall/user/", "");


        if ("data".equals(replace)) {
            showData(req, resp);
        }

    }

    /**
     * @Author: 庄左
     * @Description: 显示自己的资料
     * @DateTime: 2022/7/3 20:43
     */
    private void showData(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String token = req.getParameter("token");
        UserMessageVo user = userService.selectUserDataByToken(token);
        user.setCode(0);
        result.setCode(0);
        result.setData(user);
        resp.getWriter().println(gson.toJson(result));
    }
}
